/**
 * Used to package and output gzip. Note that this does not work properly in Vite, the specific reason is still being investigated
 * gzip压缩
 * https://github.com/anncwb/vite-plugin-compression
 */
import compressPlugin from 'vite-plugin-compression'

// 定义支持的压缩类型对象
const SUPPORTED_COMPRESSION_TYPES = {
	gzip: true,
	brotli: true,
}

function validateCompressionType(compress) {
	if (!SUPPORTED_COMPRESSION_TYPES[compress]) {
		throw new Error(`Unsupported compression type: ${compress}`)
	}
}

/**
 * 配置并生成压缩插件
 *
 * 根据指定的压缩类型（gzip或brotli），配置并生成相应的压缩插件。可以选项是否删除原始文件。
 *
 * @param {String} compress 压缩类型，可选值为'gzip'或'brotli'
 * @param {Boolean} deleteOriginFile 是否删除原始文件，默认为false
 * @returns {Array} 返回配置好的压缩插件数组
 */
export default function configCompressPlugin(compress, deleteOriginFile = false) {
	// 验证压缩类型的有效性
	validateCompressionType(compress)

	const plugins = []

	if (compress === 'gzip') {
		plugins.push(
			compressPlugin({
				ext: '.gz',
				deleteOriginFile,
			})
		)
	}

	if (compress === 'brotli') {
		plugins.push(
			compressPlugin({
				ext: '.br',
				algorithm: 'brotliCompress',
				deleteOriginFile,
			})
		)
	}
	return plugins
}
